const express = require('express')
const router = express.Router()

const mysql = require('mysql')
const { UCS2_ICELANDIC_CI } = require('mysql/lib/protocol/constants/charsets')
const db = require('../db')
const connection = mysql.createConnection(db.mysql)
connection.connect()

const sql = require('../sql')

// var jwt = require('jsonwebtoken');
var Ctoken = require('../public/token');

//时间转化为字符串时间
function formatDateTime(date) {
    var y = date.getFullYear();  
        var m = date.getMonth() + 1;  
        m = m < 10 ? ('0' + m) : m;  
        var d = date.getDate();  
        d = d < 10 ? ('0' + d) : d;  
        var h = date.getHours();  
        h=h < 10 ? ('0' + h) : h;  
        var minute = date.getMinutes();  
        minute = minute < 10 ? ('0' + minute) : minute;  
        var second=date.getSeconds();  
        second=second < 10 ? ('0' + second) : second;  
        return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;  
}

//字符串时间转化为时间
function convertDateFromString(dateString) {
    if (dateString) { 
        var arr1 = dateString.split(" "); 
        var sdate = arr1[0].split('-'); 
        var hour =arr1[1].split(':')    
        var date = new Date(sdate[0], sdate[1]-1, sdate[2],hour[0],hour[1],hour[2]); 
        return date;
        } 
}

router.get('/test', (req, res) => {
    connection.query(sql.admin.selAdmin, [req.query.admin],(err, result) => {
        if (err) throw err
        res.json(result)
    })
})

//用户登录请求
router.get('/adminLogin', (req, res) => {
    //查询所有用户
    connection.query(sql.admin.selAdmin, [req.query.admin],(err, result)=> {
        //有异常 抛出异常信息
        if(err) { throw err }      
        //判断输入的用户是否在数据库中
        if (result.length > 0) {
            //用户存在，判断密码是否正确
            if (req.query.password === result[0].password) {
                //生成token
                Ctoken.setToken(req.query.admin).then((data) => {
                    res.send({
                        isRight: true,
                        msg: '登录成功！',
                        adminToken: data,
                    })
                    return
               })   
            } else {
                res.send({
                    isRight: false,
                    msg:'密码错误！'
                })
                return
            }
        } else {
            res.send({
                isRight: false,
                msg:'用户不存在'
            }) 
            return
        }
    })

})

//获取所有用户信息
router.get('/getAllUser', (req, res) => {
    connection.query(sql.admin.selAllUser, (err, result) => {
        if (err) throw err;
        let index = 1
        result = result.map(item => {
            item.index = index++
            item.gender = item.gender === 0 ? '男' : '女'
            item.type = item.type === 0 ? '商家' : '客户'
            item.money = parseFloat(item.money).toFixed(2)+'元'
            item.imgPath = item.imgPath ===''|| item.imgPath ===null?'headPortrait.jpg':item.imgPath
            return item
        })
        res.json(result)
    })
})

//获取所有茶叶信息
router.get('/getAllTea', (req, res) => {
    connection.query(sql.admin.selAllTea, (err, result) => {
        if (err) throw err;
        let index = 1
        result = result.map(item => {
            item.index = index++
            item.price = parseFloat(item.price).toFixed(2) + '元'
            item.store = item.store + '斤'
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
        res.json(result)
    })
})

//查询所有订单
router.get('/getAllOrder', (req, res) => {
    connection.query(sql.admin.selAllOrder, (err, result) => {
        if (err) throw err;
        let index = 1
        result = result.map( (item) => {
            
            item.index = index++
            item.buyTime = formatDateTime(item.buyTime)
            item.money = parseFloat(item.money).toFixed(2) + '元'
            item.status = item.status === 0 ? '未发货' : '已发货'
            item.estatus = item.estatus === 0 ? '未评价' : '已评价'
            item.estimation = item.estimation === null ? '无评价' : item.estimation
            item.imgPath = item.imgPath === ''|| item.imgPath ===null?'oolong.jpg':item.imgPath
            return item
        })
         console.log(result)
        res.json(result)
    })
})

//删除指定用户
router.post('/deleteUser', (req, res) => {
    connection.query(sql.admin.deleteUser, [req.body.id], (err, result) => {
        if (err) throw err;
        res.json({
            isDelete: true
        })
    })
})

//更新用户信息
router.post('/updateUser', (req, res) => {
    console.log(req.body)
    let { username, password, paypwd, gender, email, phone, address, type, money,id } = req.body.userInfo
    
    connection.query(sql.admin.updateUser, [username,password,paypwd,gender,email,phone,type,parseFloat(money),address,id], (err, result) => {
        if (err) throw err;
        console.log(result)
        res.json({
            isUpdate:true
        })
        return
    })
})

//删除指定茶叶
router.post('/deleteTea', (req, res) => {
    connection.query(sql.admin.deleteTea, [req.body.teaId], (err, result) => {
        if (err) throw err;
        res.json({
            isDelete: true
        })
    })
})

//更新茶叶信息
router.post('/updateTea', (req, res) => {
    console.log(req.body)
    let {name,brand,type,price,store,teaId } = req.body.teaInfo
    
    connection.query(sql.admin.updateTea, [name,brand,type,parseFloat(price),parseInt(store),teaId], (err, result) => {
        if (err) throw err;
        console.log(result)
        res.json({
            isUpdate:true
        })
        return
    })
})

//删除指定订单
router.post('/deleteOrder', (req, res) => {
    connection.query(sql.admin.deleteOrder, [req.body.id], (err, result) => {
        if (err) throw err;
        res.json({
            isDelete: true
        })
    })
})

//更新订单信息
router.post('/updateOrder', (req, res) => {
    console.log(req.body)
    let { number,money,status,estatus,receiver,phone,address,id } = req.body.orderInfo
    req.body.orderInfo.estatus = status===0?0:estatus
    connection.query(sql.admin.updateOrder, [number,parseInt(money),status,estatus,receiver,phone,address,id], (err, result) => {
        if (err) throw err;
        console.log(result)
        res.json({
            isUpdate:true
        })
        return
    })
})
 


module.exports = router